<template>
  <div class="market-price-trend">
    <!-- 数据源切换按钮 -->
    <div class="data-source-buttons">
      <button
        :class="['source-btn', { active: currentDataSource === 'national' }]"
        @click="switchDataSource('national')"
      >
        全国市场
      </button>
      <button
        :class="['source-btn', { active: currentDataSource === 'local' }]"
        @click="switchDataSource('local')"
      >
        当地水产交易中心
      </button>
    </div>

    <!-- 图表组件 -->
    <div class="chart-container">
      <EChartsComponent :option="chartOption" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import EChartsComponent from "./EChartsComponent.vue";
import dayjs from "dayjs";
import type {
  EChartsOption,
  TooltipComponentFormatterCallbackParams,
} from "echarts";

// 扩展类型以包含 axisValue 属性（在 axis trigger 模式下可用）
type TooltipFormatterParams = TooltipComponentFormatterCallbackParams & {
  axisValue?: string;
};

// 数据源类型
type DataSource = "national" | "local";

// 当前数据源
const currentDataSource = ref<DataSource>("national");

// 切换数据源
const switchDataSource = (source: DataSource) => {
  currentDataSource.value = source;
};

// 模拟最近10天的数据
const generateMockData = (source: DataSource) => {
  const dates = [];
  const smallSizeData = []; // 小规格(80只/公斤)
  const mediumSizeData = []; // 中规格(60只/公斤)
  const largeSizeData = []; // 大规格(40只/公斤)

  // 生成最近10天的日期
  for (let i = 9; i >= 0; i--) {
    const date = dayjs().subtract(i, "day");
    dates.push(date.format("MM-DD"));
  }

  // 根据数据源设置不同的基础价格
  const basePrice =
    source === "national"
      ? { small: 60, medium: 70, large: 80 } // 全国市场价格
      : { small: 55, medium: 65, large: 75 }; // 当地水产交易中心价格（略低）

  for (let i = 0; i < 10; i++) {
    // 添加随机波动，模拟真实市场价格变化
    const variation = (Math.random() - 0.5) * 10; // ±5的波动

    smallSizeData.push(
      Number((basePrice.small + variation + Math.sin(i * 0.5) * 3).toFixed(1))
    );
    mediumSizeData.push(
      Number((basePrice.medium + variation + Math.cos(i * 0.3) * 4).toFixed(1))
    );
    largeSizeData.push(
      Number((basePrice.large + variation + Math.sin(i * 0.7) * 2).toFixed(1))
    );
  }

  return { dates, smallSizeData, mediumSizeData, largeSizeData };
};

// 响应式数据生成
const chartData = computed(() => generateMockData(currentDataSource.value));

const chartOption = computed<EChartsOption>(() => {
  const { dates, smallSizeData, mediumSizeData, largeSizeData } =
    chartData.value;

  return {
    backgroundColor: "transparent",
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "10%",
      containLabel: true,
    },
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(0, 0, 0, 0.8)",
      borderColor: "#0efcff",
      borderWidth: 1,
      textStyle: {
        color: "#0efcff",
      },
      formatter: (params: TooltipComponentFormatterCallbackParams) => {
        // 当 trigger 为 'axis' 时，params 是数组
        const paramsArray = Array.isArray(params) ? params : [params];
        // 类型断言为扩展类型以访问 axisValue 属性
        const firstParam = paramsArray[0] as TooltipFormatterParams;
        let result = `${firstParam.axisValue}<br/>`;
        paramsArray.forEach((param) => {
          result += `${param.marker}${param.seriesName}: ${param.value}元/公斤<br/>`;
        });
        return result;
      },
    },
    legend: {
      data: ["小规格(80只/公斤)", "中规格(60只/公斤)", "大规格(40只/公斤)"],
      textStyle: {
        color: "#0efcff",
      },
      top: "0%",
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: dates,
      axisLine: {
        lineStyle: {
          color: "#0efcff",
        },
      },
      axisLabel: {
        color: "#0efcff",
        fontSize: 12,
      },
    },
    yAxis: {
      type: "value",
      axisLine: {
        lineStyle: {
          color: "#0efcff",
        },
      },
      axisLabel: {
        color: "#0efcff",
        fontSize: 12,
      },
      splitLine: {
        lineStyle: {
          color: "rgba(14, 252, 255, 0.2)",
        },
      },
    },
    series: [
      {
        name: "小规格(80只/公斤)",
        type: "line",
        data: smallSizeData,
        smooth: true,
        lineStyle: {
          color: "#81d4fa",
          width: 2,
        },
        itemStyle: {
          color: "#81d4fa",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(129, 212, 250, 0.3)" },
              { offset: 1, color: "rgba(129, 212, 250, 0.05)" },
            ],
          },
        },
      },
      {
        name: "中规格(60只/公斤)",
        type: "line",
        data: mediumSizeData,
        smooth: true,
        lineStyle: {
          color: "#4fc3f7",
          width: 2,
        },
        itemStyle: {
          color: "#4fc3f7",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(79, 195, 247, 0.3)" },
              { offset: 1, color: "rgba(79, 195, 247, 0.05)" },
            ],
          },
        },
      },
      {
        name: "大规格(40只/公斤)",
        type: "line",
        data: largeSizeData,
        smooth: true,
        lineStyle: {
          color: "#29b6f6",
          width: 2,
        },
        itemStyle: {
          color: "#29b6f6",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(41, 182, 246, 0.3)" },
              { offset: 1, color: "rgba(41, 182, 246, 0.05)" },
            ],
          },
        },
      },
    ],
  };
});
</script>

<style scoped>
.market-price-trend {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.data-source-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  padding: 0 16px;
}

.source-btn {
  padding: 8px 16px;
  border: 1px solid #66ccff;
  background: transparent;
  color: #66ccff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.source-btn:hover {
  background: rgba(14, 252, 255, 0.1);
  box-shadow: 0 0 8px rgba(14, 252, 255, 0.3);
}

.source-btn.active {
  background: #0efcff;
  color: #000;
  box-shadow: 0 0 12px rgba(14, 252, 255, 0.5);
}

.chart-container {
  flex: 1;
  min-height: 0;
}
</style>
